<style lang="less">
    @import "../carDealer.less";
    .s1{
        .ivu-select-dropdown-list {
            height:200px
        }
    }

</style>
<template>
    <div class="search">
        <Row>
            <Col>
                <Card >
                    <Row>
                        <Spin fix v-if="spinShow">
                            <Icon type="ios-loading" size=60 class="demo-spin-icon-load"></Icon>
                            <div>请稍后...</div>
                        </Spin>

                        <h2 align="center">普通车商信息</h2>
                        <div style="height: 50px" >

                            <Button  @click="backToIndex" size="large"  type="primary" style="margin-right: 24px;float: right"
                                     v-if="this.typeCode != '3'">返回
                            </Button>

                            <Button  :loading="submitLoading"  @click="checkFileMethed(2)" style="margin-right: 24px;float: right"
                                    v-if="this.typeCode == '2'" size="large"  type="primary">提交
                            </Button>


                            <Button  :loading="submitLoading"  @click="checkFileMethed(1)" style="margin-right: 24px;float: right"
                                    v-if="this.typeCode == '1'" size="large"  type="primary">提交
                            </Button>

                            <Button :loading="submitLoading" @click="saveCarDealer1" style="margin-right: 24px;float: right"
                                    v-if="this.typeCode == '1'" size="large"  type="primary">保存
                            </Button>

                            <Button  :loading="submitLoading" @click="saveCarDealer2" style="margin-right: 24px;float: right"
                                     v-if="this.typeCode == '2' && this.oldStatus != '00' && this.oldStatus != '05'" size="large"  type="primary">保存
                            </Button>


                         <!--   <Button @click="addBlackList" v-if="this.typeCode == '0'" style="margin-right: 24px;width: auto;float: right"
                                    size="large"  type="primary">黑名单申请
                            </Button>-->




                        </div>


                        <Modal :title="modalTitle" v-model.trim="blackApplyVisible" :mask-closable='false' :width="500"
                               :styles="{top: '100px'}">
                            <Form ref="blackApplyForm" :model="blackApplyForm" :label-width="70"
                                  :rules="blackApplyFormValidate">
                                <FormItem label="申请原因" prop="blacklistReason">
                                    <Input v-model.trim="blackApplyForm.blacklistReason" class="w400" size="large"
                                           placeholder="请输入黑名单申请原因" type="textarea" :rows="6"/>
                                </FormItem>
                            </Form>
                            <div slot="footer" style="text-align:center;">
                                <Button type="text" @click="cancel">取消</Button>
                                <Button type="primary" @click="join">提交</Button>
                            </div>
                        </Modal>



                        <br>
                        <br>
                        <Form ref="carDealerForm" :model="carDealerForm" :label-width="130" :rules="formValidate" inline
                               v-bind:disabled="typeCode=='0'"  >
                            <Row>

                                <Col span="8">
                                <FormItem label="合作商名称" prop="channelId" style="width: 350px" v-if="!this.carDealerForm.id"  >
                                    <Select v-model="carDealerForm.channelId"  placeholder="请选择" clearable filterable style="width: 200px" class="s1"  @on-change="getChannelInfoById"  v-bind:disabled="this.typeCode != '1'">
                                        <Option v-for="(item,index) in channelData" :value="item.id" :label="item.channelFullName"  :key="index" ></Option>
                                    </Select>
                                </FormItem>
                                </Col>


                                <Col span="8">
                                <FormItem label="车商" prop="cardealerName" style="width: 350px">
                                    <Input type="text" v-model.trim="carDealerForm.cardealerName" placeholder="请输入" style="width: 200px"  maxlength="32" clearable/>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="车商代码" prop="cardealerCode" style="width: 350px">
                                    <Input type="text" v-model.trim="carDealerForm.cardealerCode" placeholder="系统自动生成" style="width: 200px" disabled/>
                                </FormItem>
                                </Col>

                            </Row>


                            <Row>
                                <Col span="8">
                                <Form-item label="合作模式" prop="cooperationMode" style="width: 350px">
                                    <radio-group v-model.trim="carDealerForm.cooperationMode">  <!--@on-change="selectRadio"-->
                                        <radio label="0">本地合作</radio>
                                        <radio label="1">异地调车</radio>
                                    </radio-group>
                                </Form-item>
                                </Col>

                                <Col span="8">
                                <Form-item label="车商性质" prop="cardealerProperties" style="width: 350px">
                                    <Select placeholder="请选择" v-model="carDealerForm.cardealerProperties" style="width: 200px">
                                        <Option value="0">汽贸</Option>
                                        <Option value="1">4S</Option>
                                        <Option value="2">其他</Option>
                                    </Select>
                                </Form-item>
                                </Col>

                                <Col span="8">
                                <FormItem label="所在区域" prop="domicLocation" style="width:350px;" >
                                    <Cascader :data="location" v-model.trim="carDealerForm.domicLocation" filterable style="width:200px;"
                                              :load-data="loadData"></Cascader>
                                </FormItem>
                                </Col>
                            </Row>

                            <Row>
                                <Col span="8">
                                <Form-item label="法人代表" prop="corporateName" style="width: 350px">
                                    <Input type="text" v-model.trim="carDealerForm.corporateName"  maxlength="32" clearable placeholder="请输入" style="width: 200px"/>
                                </Form-item>
                                </Col>

                                <Col span="8">
                                <FormItem label="手机号" prop="telephoneNumber" style="width: 350px">
                                    <Input type="text" placeholder="请输入" v-model.trim="carDealerForm.telephoneNumber"  style="width: 200px"/>
                                </FormItem>
                                </Col>

                                <Col span="8">
                                <Form-item label="统一社会信用代码" prop="socUniCrtCode" style="width: 350px">
                                    <Input type="text" clearable placeholder="请输入" v-model.trim="carDealerForm.socUniCrtCode"
                                            style="width: 200px"   v-bind:disabled="this.carDealerForm.status=='05' || this.carDealerForm.status=='00'"/>
                                </Form-item>
                                </Col>
                            </Row>
                            <Row>

                                <Col span="8">
                                    <Form-item label="注册资金(单位：万元)" prop="registeredCapital"  >
                                        <Input type="text" clearable style="width: 200px"  maxlength="32" v-model.trim="carDealerForm.registeredCapital"/>
                                    </Form-item>
                                </Col>


                                <Col span="8">
                                    <Form-item label="经纬度范围（km）" prop="longitudeLatitudeRange"  >
                                        <Input type="text" clearable style="width: 200px"  maxlength="32" v-model.trim="carDealerForm.longitudeLatitudeRange"/>
                                    </Form-item>
                                </Col>


                                <Col span="8">
                                <FormItem label="注册时间" prop="registrationTime" style="width:350px">
                                        <Date-picker type="date"
                                                    placeholder="选择日期"
                                                    v-model="carDealerForm.registrationTime"
                                                     style="width:200px">
                                        </Date-picker>

                                </FormItem>
                                </Col>


                            </Row>

                            <Row>
                                <Col span="8">
                                <FormItem label="注册省市" prop="addressinfo" >
                                    <Cascader :data="location" v-model="carDealerForm.addressinfo" style="width:200px;" @on-change="onChangeLocation"
                                              :load-data="loadData"></Cascader>
                                </FormItem>
                                </Col>


                                <Col span="8">
                                <Form-item label="详细地址" prop="address" >
                                    <Input type="text" v-model.trim="carDealerForm.address"  placeholder="请输入..." @on-blur="onBlurLocation"
                                           maxlength="150"
                                           style="width: 200px"></Input>
                                </Form-item>
                                </Col>

                                <Col span="8">
                                    <Form-item label="地址经纬度" prop="longitudeLatitude" style="width: 350px">
                                        <Input type="text" maxlength="32" clearable v-model.trim="carDealerForm.longitudeLatitude" style="width: 200px" placeholder="输入详细地址后带出"/>
                                    </Form-item>
                                </Col>



                            </Row>
                            <Row>



                                <Col span="8">
                                    <Form-item label="业务员" prop="salesMan" style="width: 350px"  :rules="Number(this.personRelCardealerSwitch) !=0?saleManSwitch:noSaleManSwitch" v-if="!this.carDealerForm.id">
                                        <Select placeholder="请选择" v-model="carDealerForm.salesMan" filterable v-bind:disabled="this.personRelCardealerSwitch == 0" class="s1"
                                                clearable style="width: 200px">
                                            <Option v-for="(item,index) in salesManData" :value="item.username" :label="item.userRealName" :key="index" >
                                            </Option>                  
                                        </Select>
                                    </Form-item>
                                </Col>

                                <Col span="8">
                                <Form-item label="备注" prop="receivingRemarks" >
                                    <Input type="textarea" :rows="4" v-model.trim="carDealerForm.receivingRemarks"
                                           maxlength="250"
                                           placeholder="请输入..." style=" width: 200px"></Input>
                                </Form-item>
                                </Col>

                                <Col span="8">
                                    <FormItem  prop="mainBrand"  label="主要经营品牌">
                                        <Tree :data="baseData" style="height:200px;overflow-y:auto;display: inline-block;" ref="baseTree" show-checkbox v-model="carDealerForm.mainBrand" @on-check-change="selectBaseTree"  multiple> </Tree>
                                    </FormItem>
                                </Col>


                            </Row>

                        </Form>

                        <Button @click="openFileUpload" size="large" v-if="showFileBut"
                                style=" color: #2b85e4;background-color:white;border:none;float:right;">{{fileText}}
                        </Button>


                    </Row>

                </Card>
            </Col>
        </Row>


        <!--<Row style="text-align: center; margin: 1% 8px 8px;border: 1px solid rgb(232, 234, 236);" v-if="isShowFile">


        </Row>-->

        <div v-if="isShowFile" >
            <!--附件-->
            <file-operation  :uploadParam="uploadParam" :isInt="canUpload" :path="path" :readOnly="readOnly"></file-operation>
        </div>


        <MapModal :mapModal="mapModal" :mapLocation="mapLocation" :mapAddress="mapAddress" @confirmLngLat="confirmLngLat" @closeMapModel="closeMapModel" />

    </div>


</template>


<script>
    import {formatDate} from "_c/iview/components/date-picker/util";
    import {
        saveCarDealerData,
        editCarDealerData,
        saveBlack,
        blackCleack,
        getCarDealerInfoById,
        getAllSPChannels,
        saveCarDealerDataToCase,
        getAllSaleManByChannelId,
    } from "@/projects/afs-channel/api/car-dealer/dealer";
    import circleLoading from "_c/circle-loading/circle-loading.vue";
    import PlaceCascade from "@/components/place-cascade";
    import {getLocation,syncFileToApply} from "@/projects/afs-channel/api/common/common";
    import {province, city, area} from "_p/afs-apply/assets/js/staticData.js";
    import {
        getAllAddressList,
        getAllCarList,
        getBrandTree
    } from "_p/afs-channel/api/common/common.js"
    import {getCarBrandById,getChannelBasicInfoById,} from  "@/projects/afs-channel/api/dealer/dealer";
    import Form from "../../../../../components/iview";
    import MapModal from '_p/afs-channel/pages/common/map/MapModal';
    import FileOperation from "_p/basic/pages/image/upload-file/fileOperation.vue";
    import {
        checkFile,
    } from "_p/basic/api/image/image-upload";
    import {deepClone} from "@/libs/utils/ObjectClone";



    export default {
        name: "carDealer-check",
        components: {
            Form,
            circleLoading
        },
        data() {
            let validate = function (rule, value, callback) {
                if (Array.isArray(value)) {//格式为：daterange、datetimerange检测
                    value.map(function (item) {
                        if (item === "") {
                            return callback("日期不能为空")
                        }
                    })
                } else { //格式为：date、datetime、year、month 检测
                    if(item === '' ||item == undefined){
                        return callback("日期不能为空")
                    }
                }
                return callback()
            };
            const validateMobile = (rule, value, callback) => {
                var reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
                if (!reg.test(value)) {
                    callback(new Error("手机号格式错误"));
                } else {
                    callback();
                }
            };
            const validatesocUniCrtCode = (rule, value, callback) => {
                var reg = /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/;
                if (!reg.test(value)) {
                    callback(new Error("统一社会信用码格式错误"));
                } else {
                    callback();
                }
            };

            const validateAmount = (rule, value, callback) => {
                var reg = /^\d+(\.\d+)?$/;
                if (!reg.test(value) && value != "") {
                    callback(new Error("数值类型格式错误"));
                } else {
                    callback();
                }
            };
            return {

                showFileBut:true,

                fileText:"上传附件",
                readOnly:true,

                //附件部分
                uploadParam: {
                    busiNo: "",
                    belongNo: "",
                    busiType: "",
                    busiData: {}
                },
                canUpload:true,
                path:"channel",

                //转圈圈
                spinShow: false,

                mapModal: false, // 地图弹窗
                mapLocation:'', // 地图定位
                mapAddress:'', // 详细地址
                canOpenMapModal: false, // 是否可以打开地图弹窗

                province:[],
                city:[],

                oldStatus:"",
                channelFullName: "",
                //主营品牌的变量
                expandLevel: 0,
                carLevel: 0,
                liveNode:false,
                //是否业务人员关联车商 1：是；0:否； 默认否
                personRelCardealerSwitch:"0",
                /**
                 * 渠道id 现在写死 后期改***************
                 * **/
                blackApplyVisible: false,
                modalTitle: "",
                notInBlackList: true,
                //判断是否是合作商非管理人员 后面要改
                isEmployee: false,

                locationData: [],
                location: [],
                isShowFile: false,
                loading: true,
                typeCode: "",
                status: "00",
                //合作商
                channelData: [],
                channelForm:{
                    channelId:"",
                    channelFullName:"",
                },
                oldChannelId:"",
                showSalesMan:false,
                //合作商下所有业务员集合
                salesManData:[],
                carDealerForm: {

                    //渠道id
                    channelId:"",
                    //更新前渠道id
                    //所在区域
                    domicLocation:[],
                    addressinfo: [
                    ],

                    locationAddressinfo: [
                        {
                            detailAddress: []
                        }
                    ],
                    associAccount: "",
                    id: "",
                    channelFullName: "",
                    cardealerName: "",
                    cardealerCode: "",
                    cooperationMode: "0",
                    cardealerProperties: "",
                    location: "",
                    corporateName: "",
                    telephoneNumber: "",
                    socUniCrtCode: "",
                    longitudeLatitude: "",
                    longitudeLatitudeRange: "",
                    salesMan: "",
                    registrationTime: "",
                    mainBrand: [],
                    address: "",
                    receivingRemarks: "",
                    status: "01",
                    cardealerType: "",

                    channelProvince: "",
                    channelCity: "",
                    channelAddrValue: [],
                    locationAddr:"",
                    //注册资金
                    registeredCapital:"",
                },

                channelAddrrLabel: "地址",
                channelAddrValue: "channelAddrValue",

                //黑名单
                blackApplyForm: {},
                //黑名单
                blackApplyFormValidate: {},


                baseData: [],
                userModalVisible: false,
                fileFrom: {
                    productName: ""
                },
                submitLoading: false,
                data: [],

                saleManSwitch:[
                    { required: true, message: "业务员不能为空", trigger: "blur"},
                ],
                noSaleManSwitch:[
                    { required: false},
                ],

                formValidate: {
                    cardealerName: [
                        {required: true, message: "车商名称不能为空", trigger: "change"}
                    ],
                    channelId: [
                        {required: true, message: "合作商名称不能为空", trigger: "change"}
                    ],
                    drawerPartyName: [
                        {required: true, message: "开票方名称不能为空", trigger: "change"}
                    ],
                    socUniCrtCode: [
                        {required: true, message: "统一社会信用代码不能为空", trigger: "change"},
                        {validator: validatesocUniCrtCode, trigger: "blur"}

                    ],
                    corporateName: [
                        {required: true, message: "法人代表不能为空", trigger: "change"}
                    ],
                    telephoneNumber: [
                        {required: true, message: "手机号码不能为空", trigger: "change"},
                        {validator: validateMobile, trigger: "blur"}
                    ],
                    cardealerProperties: [
                        {required: true, message: "车商性质不能为空", trigger: "change"}
                    ],
                    location: [
                        {required: true, type:"array", message: "所在区域不能为空", trigger: "change"}

                    ],
                    longitudeLatitude: [
                        {required: true, message: "地址经纬度不能为空", trigger: "change"}
                    ],
                    /*salesMan: [
                        {required: true, message: "业务员不能为空", trigger: "change"}
                    ],*/
                    salesMan:[],
                    address: [
                        {required: true, message: "详细地址不能为空", trigger: "change"}
                    ],
                    registrationTime: [
                        {required: true, type: "date", message: "注册时间不能为空", trigger: "change"}
                    ],
                    /*registrationTime:[
                        { required: true, validator: validate, trigger: "change"}
                    ],*/
                    mainBrand: [
                        {required: true,  message: "主要经营品牌不能为空", trigger: "change",type: "array"}
                    ],
                    domicLocation: [
                        {required: true, message: "所在区域省市不能为空", trigger: "change", type: "array"}
                    ],
                    addressinfo: [
                        {required: true, message: "注册省市不能为空", trigger: "change", type: "array"}
                    ],
                    registeredCapital:[
                        { required: true, message: "注册资金不能为空", trigger: "change"},
                        {validator: validateAmount, trigger: "change"}
                    ],
                    longitudeLatitudeRange:[
                        { required: true, message: "经纬度范围不能为空", trigger: "change"},
                    ],
                },

            };
        },

        components: {
            PlaceCascade,
            MapModal,
            FileOperation,
        },

        methods: {
            init() {
                    this.typeCode = this.afs.getPageParams(this).type
                    if (this.typeCode != '1') {
                        this.getProvinceData();
                        this.getCityData();
                        this.oldStatus=this.afs.getPageParams(this).status;
                        this.getCarDealerInfo(this.afs.getPageParams(this).dealerId);
                        this.getBaseTreeList(this.afs.getPageParams(this).dealerId);
                        this.oldChannelId=this.afs.getPageParams(this).channelId

                        console.log(this.oldStatus,"status")
                        if(this.oldStatus!='02'){
                            this.showFileBut= false;
                        }
                    }
                this.getAllChannelInfo();
                this.getLocationData();
                this.getBaseTreeList();
                if(this.typeCode != '0'){
                    this.readOnly = false;
                }else{
                    this.showFileBut= false;
                }

            },


            //查所有渠道
            getAllChannelInfo(){
                console.log("查所有渠道")
                getAllSPChannels().then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        this.channelData= res.data;
                    }
                })
            },

            // 有关省市的
            getLocationData() {
                let param = ""
                param = {
                    level: '1',
                    upperCode: '1'
                };
                getLocation(param).then((res) => {
                    if (res.code == "0000") {
                        res.data.forEach(item => {
                            // 表明是否是父节点
                            if (item.isParent) {
                                getLocation({upperCode: item.value}).then(res => {
                                    if (res.code === "0000") {
                                        item.children = res.data;
                                        this.location.push(item);
                                    }
                                })
                            }
                        })
                    }
                   // this.location.push(...res.data);
                })
            },


            //调用省市的方法
            loadData(item, callback) {
                item.loading = true;
                getLocation({upperCode: item.value}).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (item) {
                            if (item.isParent) {
                                item.loading = false;
                                item.children = [];
                            }
                        });
                        item.children = res.data;
                        item.loading = false;
                        callback();
                    }
                })
            },



            //根据车商id查询基本信息
            getCarDealerInfo(v) {
                getCarDealerInfoById(v).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        this.carDealerForm = res.data;
                        this.carDealerForm.registeredCapital = res.data.registeredCapital+"";
                        this.carDealerForm.id=v;
                        // 地址信息
                        this.carDealerForm.domicLocation = [
                            this.carDealerForm.locationProvince,
                            this.carDealerForm.locationCity
                        ];
                        this.carDealerForm.addressinfo = [
                            this.carDealerForm.channelProvince,
                            this.carDealerForm.channelCity
                        ];


                        this.carDealerForm.channelId=this.afs.getPageParams(this).channelId+"";


                        getChannelBasicInfoById(this.carDealerForm.channelId).then(res => {
                            if (res.code === "0000") {
                                this.personRelCardealerSwitch=res.data[0].personRelCardealerSwitch;
                            }
                           /* if(this.personRelCardealerSwitch == '1'){
                                this.formValidate.salesMan.unshift({required: true,  message: "业务员不能为空", trigger: "change"})
                                //  this.showSalesMan=false;
                            }else{
                                this.formValidate.salesMan=[];
                            }
                            this.showSalesMan=true;*/
                        });
                        this.getAllSaleManByChannelId();
                        setTimeout(() => {
                            this.getDetailAddress1(this.carDealerForm.channelProvince,this.carDealerForm.channelCity);
                        },1000)
                    }
                })
            },

            //主营品牌
            getBaseTreeList(v){
                let param = {
                    type:[],
                }
                getBrandTree(param).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        // 仅展开指定级数 默认一级
                        let expandLevel = this.carLevel;
                        res.data.forEach(function (e) {
                            if (expandLevel == "0") {
                                if (e.carLevel === "0") {
                                    e.expand = true;
                                }
                                if (e.children && e.children.length > 0) {
                                    e.children.forEach(function (c) {
                                        if (c.carLevel === "1") {
                                            c.expand = false;
                                        }
                                    });
                                }
                            } else {
                                if (e.children && e.children.length > 0) {
                                    e.children.forEach(function (c) {
                                        if (expandLevel == 0) {
                                            if (c.carLevel === "1") {
                                                c.expand = false;
                                            }
                                        }
                                    });
                                }
                            }
                        });
                        let mainCarSearchTemp = deepClone(res.data);
                        if(v!=null && v!="" && v!= undefined){
                            //根据渠道id查询主营品牌
                            getCarBrandById(v).then(resMainCar => {
                                this.loading = false;
                                if (resMainCar.code === "0000") {
                                    let cars = resMainCar.data;
                                    this.checkMainCarTree(mainCarSearchTemp, cars);
                                    this.baseData=mainCarSearchTemp;
                                }
                            })
                        }else{
                            this.baseData= deepClone(res.data);
                        }
                    }
                });
            },

            // 递归判断子节点
            checkMainCarTree(mainCarData, cars) {
                let that = this;
                mainCarData.forEach(function (p) {
                    if (that.hasMainCar(p, cars)=="0") {
                        //层级表示第一层级，第二层级不用勾选
                        p.checked = false;
                    }else if(that.hasMainCar(p, cars)=="1") {
                        p.checked = true;
                    }else if(that.hasMainCar(p, cars)=="2"){
                        if(p.carLevel=="0"){
                            p.checked = false;
                        }else{
                            p.checked = true;
                        }
                    }else{
                        if(p.carLevel=="0" || p.carLevel=="1" ){
                            p.checked = false;
                        }else{
                            p.checked = true;
                        }
                    }
                    if (p.children && p.children.length > 0) {
                        that.checkMainCarTree(p.children, cars);
                    }
                });
            },

            //判断主营品牌节点勾选
            hasMainCar(p, cars) {
                //flag 等于 0 表示code相等
                let flag = "0";
                for (let i = 0; i < cars.length; i++) {
                    if (p.code === cars[i].code && cars[i].code=="00" &&  cars[i].indeterminate=="false") {
                        //表示一级品牌名称非半选状态：即为全选状态，数据库只有一笔数据
                        flag="1";
                        if(cars[i].indeterminate=="false"){
                            p.indeterminate=false;
                        }else{
                            p.indeterminate=true;
                        }
                        break;
                    }else if (p.code === cars[i].code &&  cars[i].indeterminate=="false") {
                        //表示二级品牌非半选状态：即为全选状态，数据库只有一笔数据
                        flag = "2";
                        if(cars[i].indeterminate=="false"){
                            p.indeterminate=false;
                        }else{
                            p.indeterminate=true;
                        }
                        break;
                    }else if (p.code === cars[i].code){
                        //表示三级品牌非半选状态：即为全选状态，数据库只有一笔数据
                        flag = "3";
                        p.indeterminate=true;
                        break;
                    }
                }
                return flag;
            },

            //主营品牌
            selectBaseTree() {
                let brandIds = [];
                try {
                    let selectedBrandNodes = this.$refs.baseTree.getCheckedAndIndeterminateNodes();
                    selectedBrandNodes.forEach(function (e) {
                        let index = selectedBrandNodes.findIndex(m => m.indeterminate==false && m.code === e.upperCode)
                        if(index < 0) {
                            if(e.indeterminate==undefined){
                                e.indeterminate=" ";
                            }
                            if(e.spellCode==undefined){
                                e.spellCode=" ";
                            }
                            brandIds.push(e.code+","+e.title+","+e.indeterminate+","+e.carLevel+","+e.spellCode);
                            if(e.carLevel=="0" && e.indeterminate==false){
                                throw Error();
                            }
                        }
                    });
                }catch (e) {
                }

                this.carDealerForm.mainBrand=brandIds;
            },

            //返回
            backToIndex() {
                this.afs.closeTab(this);
                this.$router.push({path: '/carDealer'});
            },
            //黑名单申请
            addBlackList() {
                console.log("黑名单申请开始！");
                this.modalTitle = "确认将合作商加入黑名单吗？";
                this.blackApplyVisible = true;
            },
            cancel() {
                //关闭黑名单窗口
                this.blackApplyVisible = false;
            },
            //申请加入黑名单
            join() {
                console.log("普通车商黑名单保存开始！");
                let params = {
                    //黑名单类型：车商
                    blacklistType: '05',
                    //黑名单名称
                    blackName: this.carDealerForm.cardealerName,
                    //证件类型：组织机构代码
                    idType: '02',
                    idCode: this.carDealerForm.socUniCrtCode,
                    carDealers: "01",
                    //黑名单原因
                    blacklistReason: this.blackApplyForm.blacklistReason
                }
                saveBlack(params).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success("申请成功！");
                        this.cancel();
                    }
                }).catch(() => {
                    this.$Message.success("申请失败！");
                });
            },


            //新增车商时保存为草稿
            saveCarDealer1() {
                if(this.carDealerForm.id !=null && this.carDealerForm.id!=undefined && this.carDealerForm.id !=""){
                    this.saveCarDealer2();
                }else {
                    this.status = "02";
                    this.$refs.carDealerForm.validate(valid => {
                        if (valid) {

                            //验证黑名单
                            let blackParams = {
                                //黑名单类型：车商
                                blacklistType: '05',
                                //黑名单名称
                                blackName: this.carDealerForm.cardealerName,
                                //证件类型：统一社会信息代码
                                idType: '02',
                                //统一社会信用代码
                                idCode: this.carDealerForm.socUniCrtCode,
                                //车商类型 :普通车商
                                carDealers: "01",
                            };
                            blackCleack(blackParams).then(res => {
                                if (res.code === "0000") {
                                    if (res.weatherBlackList == "1") {
                                        this.$Message.error("该车商已存在黑名单信息库中");
                                        return false;
                                    } else if (res.weatherBlackList == "0") {
                                        //如果不是管理员
                                        if (this.isEmployee) {
                                            this.carDealerForm.associAccount = "当前操作人员";
                                            this.carDealerForm.salesMan = "当前操作人员";
                                        } else {
                                            //是管理员
                                            this.carDealerForm.associAccount = this.carDealerForm.salesMan;
                                        }
                                        let time = "";
                                        if(this.carDealerForm.registrationTime != null || this.carDealerForm.registrationTime !=""){
                                            time =formatDate(this.carDealerForm.registrationTime,"yyyy-MM-dd")
                                            //time =this.carDealerForm.registrationTime.toLocaleDateString();
                                        }
                                        let param = {
                                            channelCoopeCardealerTemp: {
                                                channelId: this.carDealerForm.channelId,
                                                cardealerType: "01",
                                                associAccount: this.carDealerForm.associAccount,
                                                status: this.status,
                                                createBy:"channelAdmin",
                                            },

                                            commonCarDealer: {
                                                id:this.carDealerForm.id,
                                                cardealerCode:this.carDealerForm.cardealerCode,
                                                cardealerName: this.carDealerForm.cardealerName,
                                                cooperationMode: this.carDealerForm.cooperationMode,
                                                cardealerProperties: this.carDealerForm.cardealerProperties,
                                                //所在区域省市
                                                locationProvince: this.carDealerForm.domicLocation[0],
                                                locationCity: this.carDealerForm.domicLocation[1],
                                                corporateName: this.carDealerForm.corporateName,
                                                telephoneNumber: this.carDealerForm.telephoneNumber,
                                                socUniCrtCode: this.carDealerForm.socUniCrtCode,
                                                longitudeLatitude: this.carDealerForm.longitudeLatitude,
                                                longitudeLatitudeRange: this.carDealerForm.longitudeLatitudeRange,
                                                salesMan: this.carDealerForm.salesMan,
                                                registrationTime:time,
                                                //注册省市
                                                channelProvince: this.carDealerForm.addressinfo[0],
                                                channelCity: this.carDealerForm.addressinfo[1],
                                                address: this.carDealerForm.address,
                                                receivingRemarks: this.carDealerForm.receivingRemarks,
                                                registeredCapital: this.carDealerForm.registeredCapital,
                                                status: this.status
                                            },
                                            mainBrand:this.carDealerForm.mainBrand,
                                        };
                                        this.spinShow= true;
                                        saveCarDealerData(param).then(res => {
                                            this.loading = false;
                                            if (res.code === "0000") {
                                                this.carDealerForm.id = res.data.id;
                                                this.$Message.success("保存成功");
                                                this.carDealerForm.cardealerCode = res.data.cardealerCode;
                                                this.carDealerForm.id = res.data.id;
                                                this.openFileUpload();
                                                this.spinShow = false;
                                            }
                                        }).catch(() => {
                                            this.spinShow= false;
                                        });
                                    }
                                }
                            }).catch(() => {
                                this.$Message.error("未知错误,请联系管理员！");
                                this.loading = false;
                                this.spinShow= false;
                            });
                        }
                    });
                }

            },
            //提交
            submitCarDealer() {
                if(this.carDealerForm.id !=null && this.carDealerForm.id!=undefined && this.carDealerForm.id !=""){
                    this.editCarDealer();
                }else {
                    this.status = "00";
                    this.loading = true;
                    this.$refs.carDealerForm.validate(valid => {
                        if (valid) {
                            //验证黑名单
                            let blackParams = {
                                //黑名单类型：车商
                                blacklistType: '05',
                                //黑名单名称
                                blackName: this.carDealerForm.cardealerName,
                                //证件类型：统一社会信息代码
                                idType: '02',
                                //统一社会信用代码
                                idCode: this.carDealerForm.socUniCrtCode,
                                //车商类型 :普通车商
                                carDealers: "01",
                            };
                            blackCleack(blackParams).then(res => {
                                if (res.code === "0000") {
                                    if (res.weatherBlackList == "1") {
                                        this.$Message.error("该车商已存在黑名单信息库中");
                                    } else if (res.weatherBlackList == "0") {
                                        //如果不是管理员
                                        if (this.isEmployee) {
                                            this.carDealerForm.associAccount = "当前操作人员";
                                            this.carDealerForm.salesMan = "当前操作人员";
                                        } else {
                                            //是管理员
                                            this.carDealerForm.associAccount = this.carDealerForm.salesMan;
                                        }
                                        let time = "";
                                        if(this.carDealerForm.registrationTime != null || this.carDealerForm.registrationTime !=""){
                                            time =formatDate(this.carDealerForm.registrationTime,"yyyy-MM-dd")
                                            //time =this.carDealerForm.registrationTime.toLocaleDateString();
                                        }
                                        let param = {
                                            channelCoopeCardealerTemp: {
                                                channelId: this.carDealerForm.channelId,
                                                cardealerType: "01",
                                                associAccount: this.carDealerForm.associAccount,
                                                status: this.status,
                                                createBy:"channelAdmin",
                                            },
                                            commonCarDealer: {
                                                id: this.carDealerForm.id,
                                                cardealerName: this.carDealerForm.cardealerName,
                                                cardealerCode:this.carDealerForm.cardealerCode,
                                                cooperationMode: this.carDealerForm.cooperationMode,
                                                cardealerProperties: this.carDealerForm.cardealerProperties,
                                                //所在区域省市
                                                locationProvince: this.carDealerForm.domicLocation[0],
                                                locationCity: this.carDealerForm.domicLocation[1],
                                                corporateName: this.carDealerForm.corporateName,
                                                telephoneNumber: this.carDealerForm.telephoneNumber,
                                                socUniCrtCode: this.carDealerForm.socUniCrtCode,
                                                longitudeLatitude: this.carDealerForm.longitudeLatitude,
                                                longitudeLatitudeRange: this.carDealerForm.longitudeLatitudeRange,
                                                salesMan: this.carDealerForm.salesMan,
                                                registrationTime: time,
                                                //注册省市
                                                channelProvince: this.carDealerForm.addressinfo[0],
                                                channelCity: this.carDealerForm.addressinfo[1],
                                                address: this.carDealerForm.address,
                                                receivingRemarks: this.carDealerForm.receivingRemarks,
                                                registeredCapital: this.carDealerForm.registeredCapital,
                                                status: this.status
                                            },
                                            mainBrand: this.carDealerForm.mainBrand,
                                        };
                                        this.spinShow= true;
                                        saveCarDealerData(param).then(res => {
                                            this.loading = false;
                                            if (res.code === "0000") {
                                                this.carDealerForm.id = res.data.id;
                                                //同步案件服务
                                                this.$Message.success("提交成功");
                                                this.spinShow= false;
                                                this.afs.closeTab(this);
                                                this.$router.push({path: '/carDealer'});
                                            }

                                        }).catch(() => {
                                            this.spinShow= false;
                                        });
                                    }
                                }
                            }).catch(() => {
                                this.$Message.error("未知错误,请联系管理员！");
                                this.spinShow= false;
                            });

                        }
                    });
                }
            },

            //编辑并启用
            editCarDealer() {
                this.status = "00";
                this.loading = true;
                this.selectBaseTree();
                this.$refs.carDealerForm.validate(valid => {
                    if (valid) {

                        //验证黑名单
                        let blackParams = {
                            //黑名单类型：车商
                            blacklistType: '05',
                            //黑名单名称
                            blackName: this.carDealerForm.cardealerName,
                            //证件类型：统一社会信息代码
                            idType: '02',
                            //统一社会信用代码
                            idCode: this.carDealerForm.socUniCrtCode,
                            //车商类型 :普通车商
                            carDealers: "01",
                        };
                        blackCleack(blackParams).then(res => {
                            if (res.code === "0000") {
                                if (res.weatherBlackList == "1") {
                                    this.$Message.error("该车商已存在黑名单信息库中");
                                } else if (res.weatherBlackList == "0") {

                                    let time = "";
                                    if(this.carDealerForm.registrationTime != null || this.carDealerForm.registrationTime !=""){
                                        time =formatDate(this.carDealerForm.registrationTime,"yyyy-MM-dd")
                                        //time =this.carDealerForm.registrationTime.toLocaleDateString();
                                    }
                                    let param = {
                                        oldChannelId:this.oldChannelId,
                                        //目前写死 后面要改********
                                        channelCoopeCardealerTemp: {
                                            //目前写死 后面要改********
                                            channelId: this.carDealerForm.channelId,
                                            cardealerType: "01",
                                            associAccount: this.carDealerForm.salesMan,
                                            status: this.status,
                                            createBy:"channelAdmin",
                                        },
                                        commonCarDealer: {
                                            id: this.carDealerForm.id,
                                            cardealerCode:this.carDealerForm.cardealerCode,
                                            cardealerName: this.carDealerForm.cardealerName,
                                            cooperationMode: this.carDealerForm.cooperationMode,
                                            cardealerProperties: this.carDealerForm.cardealerProperties,
                                            //所在省市
                                            locationProvince: this.carDealerForm.domicLocation[0],
                                            locationCity: this.carDealerForm.domicLocation[1],
                                            corporateName: this.carDealerForm.corporateName,
                                            telephoneNumber: this.carDealerForm.telephoneNumber,
                                            socUniCrtCode: this.carDealerForm.socUniCrtCode,
                                            longitudeLatitude: this.carDealerForm.longitudeLatitude,
                                            longitudeLatitudeRange: this.carDealerForm.longitudeLatitudeRange,
                                            salesMan: this.carDealerForm.salesMan,
                                            registrationTime:time,
                                            channelProvince: this.carDealerForm.addressinfo[0],
                                            channelCity: this.carDealerForm.addressinfo[1],
                                            address: this.carDealerForm.address,
                                            receivingRemarks: this.carDealerForm.receivingRemarks,
                                            registeredCapital: this.carDealerForm.registeredCapital,
                                            status: this.status
                                        },
                                        mainBrand:this.carDealerForm.mainBrand,
                                    };
                                    this.spinShow= true;
                                    editCarDealerData(param).then(res => {
                                        this.loading = false;
                                        if (res.code === "0000") {
                                            this.$Message.success("提交成功");
                                            this.spinShow= false;

                                            //同步影像件到进件服务
                                            let fileId = this.carDealerForm.id;
                                            let belongNo = this.carDealerForm.channelId
                                            this.syncFileToApply(fileId,belongNo)

                                            this.afs.closeTab(this);
                                            this.$router.push({path: '/carDealer'});
                                        }
                                    }).catch(() => {
                                        this.spinShow= false;
                                    });
                                }
                            }
                        }).catch(() => {
                            this.$Message.error("未知错误,请联系管理员！");
                            this.spinShow= false;
                        });

                    }
                });
            },

            syncFileToApply(fileId,belongNo){
                syncFileToApply(fileId,belongNo).then(result => {
                })
            },

            //编辑车商时保存为草稿
            saveCarDealer2() {
                this.status = "02";
                this.loading = true;
                this.selectBaseTree();
                this.$refs.carDealerForm.validate(valid => {
                    if (valid) {

                        //验证黑名单
                        let blackParams = {
                            //黑名单类型：车商
                            blacklistType: '05',
                            //黑名单名称
                            blackName: this.carDealerForm.cardealerName,
                            //证件类型：统一社会信息代码
                            idType: '02',
                            //统一社会信用代码
                            idCode: this.carDealerForm.socUniCrtCode,
                            //车商类型 :普通车商
                            carDealers: "01",
                        };
                        blackCleack(blackParams).then(res => {
                            if (res.code === "0000") {
                                if (res.weatherBlackList == "1") {
                                    this.$Message.error("该车商已存在黑名单信息库中");
                                } else if (res.weatherBlackList == "0") {

                                    let time = "";
                                    if(this.carDealerForm.registrationTime != null || this.carDealerForm.registrationTime !=""){
                                        time =formatDate(this.carDealerForm.registrationTime,"yyyy-MM-dd")
                                        //time =this.carDealerForm.registrationTime.toLocaleDateString();
                                    }
                                    let param = {
                                        oldChannelId:this.oldChannelId,
                                        //目前写死 后面要改********
                                        channelCoopeCardealerTemp: {
                                            //目前写死 后面要改********
                                            channelId: this.carDealerForm.channelId,
                                            cardealerType: "01",
                                            associAccount: this.carDealerForm.salesMan,
                                            status: this.status,
                                            createBy:"channelAdmin",
                                        },
                                        commonCarDealer: {
                                            id: this.carDealerForm.id,
                                            cardealerCode:this.carDealerForm.cardealerCode,
                                            cardealerName: this.carDealerForm.cardealerName,
                                            cooperationMode: this.carDealerForm.cooperationMode,
                                            cardealerProperties: this.carDealerForm.cardealerProperties,
                                            //所在省市
                                            locationProvince: this.carDealerForm.domicLocation[0],
                                            locationCity: this.carDealerForm.domicLocation[1],
                                            corporateName: this.carDealerForm.corporateName,
                                            telephoneNumber: this.carDealerForm.telephoneNumber,
                                            socUniCrtCode: this.carDealerForm.socUniCrtCode,
                                            longitudeLatitude: this.carDealerForm.longitudeLatitude,
                                            longitudeLatitudeRange: this.carDealerForm.longitudeLatitudeRange,
                                            salesMan: this.carDealerForm.salesMan,
                                            registrationTime: time,
                                            channelProvince: this.carDealerForm.addressinfo[0],
                                            channelCity: this.carDealerForm.addressinfo[1],
                                            address: this.carDealerForm.address,
                                            receivingRemarks: this.carDealerForm.receivingRemarks,
                                            registeredCapital: this.carDealerForm.registeredCapital,
                                            status: this.status
                                        },
                                        mainBrand:this.carDealerForm.mainBrand,
                                    };
                                    this.spinShow= true;
                                    editCarDealerData(param).then(res => {
                                        this.loading = false;
                                        if (res.code === "0000") {
                                            this.$Message.success("保存成功");
                                            this.carDealerForm.cardealerCode=res.data.cardealerCode;
                                            this.carDealerForm.id=res.data.id;
                                            this.openFileUpload();
                                            this.spinShow= false;
                                            //同步影像件到进件服务
                                            let fileId = this.carDealerForm.id;
                                            let belongNo = this.carDealerForm.channelId
                                            this.syncFileToApply(fileId,belongNo)
                                        }

                                    }).catch(() => {
                                        this.spinShow= false;
                                    });
                                }
                            }
                        }).catch(() => {
                            this.$Message.error("未知错误,请联系管理员！");
                            this.spinShow= false;
                        });

                    }
                });
            },

            //根据合作商id查询相关的信息
            getChannelInfoById(){
                this.carDealerForm.salesMan="";
                let id = this.carDealerForm.channelId;
                if(id=="" || id==undefined || id== null){
                    this.formValidate.salesMan=[];
                    this.personRelCardealerSwitch="0";
                    return;
                }
                getChannelBasicInfoById(id).then(res => {
                    if (res.code === "0000") {
                        this.personRelCardealerSwitch=res.data[0].personRelCardealerSwitch;
                    }
                    if(this.personRelCardealerSwitch == '1'){
                      //  this.formValidate.salesMan.unshift({required: true,  message: "业务员不能为空", trigger: "blur"})
                      //  this.showSalesMan=false;

                        let businessType ="01";
                        //获取当前合作商下面的所有业务员
                        getAllSaleManByChannelId(id,businessType).then(res => {
                            if (res.code === "0000") {
                                this.salesManData=res.data;
                            }
                        });

                    }else{
                      //  this.formValidate.salesMan=[];
                    }
                    this.showSalesMan=true;
                });
            },

            getAllSaleManByChannelId(){
            //获取当前合作商下面的所有业务员
                let businessType ="01";
            getAllSaleManByChannelId(this.carDealerForm.channelId,businessType).then(res => {
                if (res.code === "0000") {
                    this.salesManData=res.data;
                    }
                });
            },

            handleBack() {
                this.isShowFile = !this.isShowFile;
            },


            openFileUpload() {
               if(!this.carDealerForm.id || !this.carDealerForm.channelId){
                   this.$Message.error("请先保存基本信息!");
                   return false;
               }
                this.isShowFile = !this.isShowFile;
                if (this.isShowFile) {
                    this.fileText = "关闭附件";
                } else {
                    this.fileText = "上传附件";
                }

                if(this.carDealerForm.id && this.isShowFile){
                    this.initGetFilterParams();
                }
            },

            // 地图弹窗
            openMapModal(){
                let address = this.mapLocation
                let detial = this.carDealerForm.address
                console.log(address,detial);
                this.mapModal = true;
            },
            // 确认经纬度
            confirmLngLat(data){
                console.log('选择的经纬度为：',data);
                this.mapModal = false;
                if(data && data.latitude && data.longitude){
                    //this.carDealerForm = Object.assign({},this.carDealerForm,data)
                    this.carDealerForm.longitudeLatitude=data.longitude+","+ data.latitude;
                    /*this.carDealerForm.latitude=data.latitude.toString();
                    this.carDealerForm.longitude=data.longitude.toString();*/
                }
            },
            closeMapModel(){
                this.mapModal = false;
            },
            onBlurLocation(){
                this.$refs.carDealerForm.validateField('address',(e) => {
                    console.log('-------------------');
                    console.log('address',e,typeof e);
                    console.log('mapLocation',this.mapLocation);
                    if(!e) {
                        this.mapAddress = this.carDealerForm.address;
                        if(this.mapLocation) {
                            this.canOpenMapModal = true;
                            this.openMapModal();
                        }
                    }

                })

            },
            onChangeLocation(value, data){
                console.log(value);
                let str='';
                if(Array.isArray(data) && data.length){
                    data.forEach(ele =>{
                        str += (ele.label ? ele.label : '');
                    })
                    this.mapLocation = str;
                    if(this.mapAddress) {
                        this.canOpenMapModal = true;
                    }
                }
            },
            //反向解析省市地址
            getProvinceData() {
                let param = {level:"1",upperCode: "1"};

                getLocation(param).then(res => {
                    if(res.code === "0000"){
                        this.province=res.data;
                    }
                });
            },
            getCityData() {
                let param = {level:2,upperCode:''};
                getLocation(param).then(res => {
                    if (res.code == "0000") {
                        this.city=res.data;
                    }
                });
            },

            getDetailAddress1(registeredProvince,registeredCity){
                if(registeredProvince!="" && registeredCity!=""){
                    let province="";
                    let city="";
                    for(let i=0;i<this.province.length;i++){
                        if(this.province[i].value==registeredProvince){
                            province=this.province[i].label;
                        }
                    };
                    for(let i=0;i<this.city.length;i++){
                        if(this.city[i].value==registeredCity){
                            city=this.city[i].label;
                        }
                    };
                    this.mapLocation=province+city;
                }
            },
            initGetFilterParams() {
                this.uploadParam.busiNo = this.carDealerForm.id;
                this.uploadParam.belongNo = this.carDealerForm.channelId;
                this.uploadParam.busiData = {};
                this.uploadParam.busiType = "CommonCarDealer";
            },

            //影像件校验
            checkFileMethed(v) {
                console.log(this.uploadParam.busiNo)
                if(this.showFileBut){
                    if (this.carDealerForm.id) {
                        this.initGetFilterParams();
                        checkFile(this.uploadParam).then(res => {
                            if (res.code === '0000' && v== 2) {
                                this.editCarDealer();
                            }else if(res.code === '0000' && v== 1){
                                this.submitCarDealer();
                            }
                        }).catch(() => {
                            this.$Message.error("请录入影像资料！");
                        });
                    } else {
                        this.$Message.error("请先保存基本信息!");
                    }
                }else{
                    if (v== 2) {
                        this.editCarDealer();
                    }else if(v== 1){
                        this.submitCarDealer();
                    }
                }
            },


        },
        mounted() {
            this.init();
        }
    };
</script>
